package com.campus_assistant.config.db;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

@Component
@Primary
public class DynamicDataSource implements DataSource, InitializingBean {
    public static ThreadLocal<String> dbName=new ThreadLocal<>();
    @Autowired
    DataSource dataSource1;
    @Autowired
    DataSource dataSource2;
    @Autowired
    DataSource dataSource3;
    @Autowired
    DataSource dataSource4;
    @Override
    public Connection getConnection() throws SQLException {
        if(dbName.get().equals("db1")){
            return dataSource1.getConnection();
        }else if (dbName.get().equals("db2")){
            return dataSource2.getConnection();
        }else if (dbName.get().equals("db3")){
            return dataSource3.getConnection();
        }else if (dbName.get().equals("db4")){
            return dataSource4.getConnection();
        }else {
            System.out.println("请选择数据库");
            return null;
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        dbName.set("db1");
    }
}
